package poc.gridfs;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GridFSMain {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(GridFSMain.class);
  
    
    /**
     * <p>Method ：main
     * <p>Description : 
     * 参数1：dburl
     * 参数2：file uri
     * 参数3：线程数
     * java -jar gridfs-0.1.jar mongodb://192.168.1.123:27017/haha E:\git\gridfs\src\test\resources\book.pdf 5
     * @param args 
     * @author  gulixing@msn.com
     * @version 1.0.0
     */
    public static void main(String[] args) {
    	//mvn assembly:assembly
    	int threadCount=1;
    	if(args.length>2){
    		threadCount = Integer.valueOf(args[2]);
    	}
    	//创建一个可重用固定线程数的线程池
        ExecutorService pool = Executors.newFixedThreadPool(threadCount+1);

        //创建实现了Runnable接口对象，Thread对象当然也实现了Runnable接口

        GridFSThread[] threads = new GridFSThread[threadCount];
        
        final CountThread ct = new CountThread();
        
        for (int i = 0; i < threadCount; i++) {
        	threads[i] = new GridFSThread(args[0],args[1]);
        	ct.add(threads[i]);
        	//将线程放入池中进行执行
        	pool.execute(threads[i]);
		}
        logger.info("now:{}",new Date());
        pool.execute(ct);
        
        //进程中止时进行完整统计
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                logger.info("system is shutting down");
                logger.info("all {} records has inserted.",CountThread.all);
                long now = new Date().getTime();
                double avg = CountThread.all/((double)(now-ct.start)/1000);
                logger.info("average {} records per second.",avg);
                logger.info("now:{}",new Date());

            }
        });
        
        //关闭线程池
        pool.shutdown();   
	}
}